package org.icsdt.sp.fragments;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

import org.icsdt.sp.R;
import org.icsdt.sp.domain.Millenium;
import org.icsdt.sp.service.BDService;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MilleniumAdapter extends BaseAdapter {
    private LayoutInflater inflater;
    private final Activity context;
    private final List<Millenium> lista;

    public MilleniumAdapter(Activity context, List<Millenium> lista) {
	this.context = context;
	this.lista = lista;
	this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    public int getCount() {
	return lista != null ? lista.size() : 0;
    }
    public Object getItem(int posicao) {
	return lista != null ? lista.get(posicao) : null;
    }
    public long getItemId(int posicao) {
	return posicao;
    }

    public View getView(int posicao, View view, ViewGroup parent) {
	Millenium mi = lista.get(posicao);
	BDService.loadSolicitacao(mi.solicitacao);
	BDService.loadOcorrencia(mi.solicitacao.ocorrencia);
	
	view = inflater.inflate(R.layout.solicitacao_item, null);
	TextView tDp = (TextView) view.findViewById(R.id.tDp);
	TextView tOcorrencia = (TextView) view.findViewById(R.id.tOcorrencia);
	TextView tTipo = (TextView) view.findViewById(R.id.tTipo);
	TextView tData = (TextView) view.findViewById(R.id.tData);
	
	String dp = mi.solicitacao.ocorrencia.dp;
	tDp.setText(dp.substring(0, dp.indexOf(' ')));
	tOcorrencia.setText(mi.solicitacao.ocorrencia.numero);
	tTipo.setText(mi.solicitacao.tipo);

	String data[] = mi.solicitacao.data.split(" ");  
	Date date = Date.valueOf(data[0]);
	Date date_atual = new Date(System.currentTimeMillis());
	//Date date_atual = (Date) Calendar.getInstance().getTime();

	if (date.compareTo(date_atual) != 0) {
	    SimpleDateFormat sdf = new SimpleDateFormat("dd 'de' MMM", new Locale("pt","BR"));
	    tData.setText(sdf.format(date));
	}
	else 
	{
	    String time[]  = data[1].split(":");
	    tData.setText(time[0] + "h" + time[1] + "m");
	}
	return view;
    }
}
